package com.youlu.campus.admin.auth.service.impl;

import com.youlu.campus.admin.auth.common.AuthConstants;
import com.youlu.campus.admin.auth.entity.exception.AuthErrorCode;
import com.youlu.campus.admin.auth.service.RsaService;
import com.youlu.campus.admin.auth.shiro.exception.AuthException;
import com.youlu.campus.admin.utils.RSACoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Map;

@Service
public class RsaServiceImpl implements RsaService {
    private Logger logger = LoggerFactory.getLogger(RsaServiceImpl.class);

    @Override
    public String publicKey(String key) {
        logger.debug("RsaServiceImpl.publicKey param key:{}", key);
        String publicKey = null;
        try {
            Map<String, Key> keyMap = RSACoder.initKey();
            publicKey = RSACoder.getPublicKey(keyMap);
            String privateKey = RSACoder.getPrivateKey(keyMap);

            String redisKey = String.format(AuthConstants.REDIS_MSG_PRIVATE_KEY, key);
//            jc.set(redisKey, privateKey);
//            logger.debug("设置: {} 的私钥: {} 过期时间为1分钟", key, privateKey);
//            jc.expire(redisKey, 60);
        } catch (Exception ex) {
            logger.error("获取公钥的时候发生异常", ex);
            throw new AuthException(AuthErrorCode.PUBLIC_KEY_ERROR);
//            ExceptionUtils.business(AuthErrorCode.PUBLIC_KEY_ERROR);
        }
        return publicKey;
    }

    @Override
    public String decrypt(String text, String key) {
        logger.debug("RsaServiceImpl.publicKey param key:{}, text:{}", key, text);
        try {
            String redisKey = String.format(AuthConstants.REDIS_MSG_PRIVATE_KEY, key);
//            String privateKey = jc.get(redisKey);
//            if (StringUtils.isEmpty(privateKey)) {
//                logger.warn("RsaServiceImpl.decrypt redisKey:{} privateKey is empty", redisKey);
//                ExceptionUtils.business(AuthErrorCode.DECRYPT_ERROR);
//            }
//            logger.debug("RsaServiceImpl.decrypt redisKey:{}, privateKey:{}", redisKey, privateKey);
//            return new String(RSACoder.decryptByPrivateKey(text, privateKey));
            return new String(RSACoder.decryptByPrivateKey(text, ""));
        } catch (Exception ex) {
            logger.warn("解密的时候发生异常:{}", ex);
            throw new AuthException(AuthErrorCode.DECRYPT_ERROR);
//            ExceptionUtils.business(AuthErrorCode.DECRYPT_ERROR);
        }
    }
}
